import os
import time
import yaml
import numpy as np
from PIL import Image
import joblib
import pickle

# 加载配置文件
with open('0_setting.yaml', 'r', encoding='utf-8') as f:
    setting = yaml.load(f, Loader=yaml.Loader)


def save_pickle(data, filename):
    with open(filename, 'wb') as f:
        pickle.dump(data, f)


# 获取配置文件中的键对应的值
def get(key):
    return setting[key]


# 图像预处理函数
def preprocess_image(file_name, new_size):
    # 读取图像并将其转换为灰度图像
    img = Image.open(file_name).convert('L')

    # 将图像调整为新的大小
    img = img.resize(new_size, Image.ANTIALIAS)

    # 将图像展平为一维数组
    img = np.asarray(img).reshape(-1)

    return img


# 序列化对象并保存到本地
def dump(obj, name, loc):
    start = time.time()
    print(f"Saving {name} to {loc}...")
    joblib.dump(obj, loc)
    end = time.time()
    print(f"Saved! Location: {loc}, Size: {os.path.getsize(loc) / 1024 / 1024:.3f}M")
    print(f"Time taken: {end - start:.3f} seconds")


# 从本地加载对象并反序列化
def load(name, loc):
    print(f"Loading {name} from {loc}...")
    obj = joblib.load(loc)
    return obj
